<?php
/**
 * Created by PhpStorm.
 * Script Name: Moments.php
 * Create: 2021/12/21 12:00
 * Description: 朋友圈
 * Author: fudaoji<fdj@kuryun.cn>
 */

namespace plugin\wechat\app\tenant\controller;
use app\common\constant\Common;
use app\common\service\Media as MediaService;
use app\common\service\Tenant as TenantService;
use plugin\wechat\app\model\BotMoments as MomentsM;
use plugin\wechat\app\model\BotMomentsFollow as MomentsFollowM;
use plugin\wechat\app\model\Bot as BotM;
use plugin\wechat\app\model\BotMember as MemberM;
use plugin\wechat\app\service\Bot as BotService;
use plugin\wechat\app\service\BotFriend as FriendService;
use plugin\wechat\app\service\BotMoments as MomentsService;
use support\Request;

class Botmoments extends BotBase
{
    /**
     * @var MomentsM
     */
    protected $model;
    /**
     * @var BotM
     */
    private $botM;
    /**
     * @var MemberM
     */
    private $memberM;
    /**
     * @var MomentsFollowM
     */
    private $momentsFollowM;

    /**
     * 初始化
     */
    public function __construct()
    {
        parent::__construct();
        $this->model = new MomentsM();
        $this->botM = new BotM();
        $this->memberM = new MemberM();
        $this->momentsFollowM = new MomentsFollowM();
    }

    /**
     * 朋友列表
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \Exception
     * @throws \Psr\SimpleCache\InvalidArgumentException
     */
    public function moments(){
        $wxid = input('wxid', $this->bot['uin']);
        $pyq_id = input('pyq_id', '');
        $has_more = true;

        $client = BotService::getRobotclient($this->bot);
        if($wxid == $this->bot['uin']){
            $res = $client->getMoments([
                'robot_wxid' => $this->bot['uin'],
                'pyq_id' => $pyq_id,
                'num' => 10
            ]);
            $member = $this->bot;
            $member['nickname_show'] = '我';
            $heads = FriendService::getWxidToHead();
            $heads[$this->bot['uin']] = $this->bot['headimgurl'];
        }else{
            $res = $client->getFriendMoments([
                'robot_wxid' => $this->bot['uin'],
                'to_wxid' => $wxid,
                'pyq_id' => $pyq_id,
                'num' => 10
            ]);
            $member = FriendService::getMember($wxid);
            $member['nickname_show'] = $member['nickname'];
            $heads = [$member['wxid'] => $member['headimgurl']];
        }

        if(!empty($res['data'])){
            $list = $res['data'];
            foreach ($list as $k => $v){
                $v = array_merge($v, MomentsService::decodeObject($v['object']));
                unset($v['object']);
                $list[$k] = $v;
            }
        }else{
            $has_more = false;
            $list = [];
        }

        $assign = [
            'list' => $list,
            'member' => $member,
            'has_more' => $has_more,
            'heads' => $heads
        ];
        return $this->show($assign);
    }

    /**
     * 好友列表
     * @return mixed
     * Author: fudaoji<fdj@kuryun.cn>
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function pull(){
        if($this->bot['protocol'] != BotService::PROTOCOL_MY){
            return $this->error("当前机器人不支持朋友圈接口，请切换为西瓜框架！");
        }
        $search_key = input('search_key', '');
        $where = [];
        !empty($search_key) && $where[] = ['remark_name|nickname', 'like', '%'.$search_key.'%'];
        $assign = [
            'friend_list' => FriendService::getFriendList($this->bot['uin'], $where)
        ];
        return $this->show($assign);
    }

    /**
     * 接口发表记录
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function index()
    {
        if (request()->isPost()) {
            $post_data = input('post.');
            $where = [
                $this->tenantWhere(),
                ['bot_id' ,'=', $this->bot['id']],
            ];
            !empty($post_data['search_key']) && $where[] = ['content', 'like', '%' . $post_data['search_key'] . '%'];
            $query = $this->model->where($where);
            $total = $query->count();
            if ($total) {
                $list = $query->page($post_data['page'], $post_data['limit'])
                    ->order('id', 'desc')
                    ->select();
                foreach ($list as $k => $v){
                    $v['bot_id'] = implode(',', BotService::getIdToTitle(0, [['id','in', $v['bot_id']]]));
                    $v['media_title'] = MediaService::getMediaTitle(intval($v['media_id']), $v['media_type']);
                    $list[$k] = $v;
                }
            }else{
                $list = [];
            }

            return $this->success('success', '', ['total' => $total, 'list' => $list]);
        }

        $builder = new ListBuilder();
        $builder->setSearch([
            ['type' => 'text', 'name' => 'search_key', 'title' => '关键词', 'placeholder' => '']
        ])
            ->addTopButton('addnew', ['text' => '发朋友圈'])
            ->addTopButton('addnew', ['title' => '跟圈设置','text' => '跟圈设置', 'href' => url('follow'), 'class' => 'layui-btn-warm'])
            ->addTableColumn(['title' => '机器人', 'field' => 'bot_id', 'minWidth' => 90])
            ->addTableColumn(['title' => '类型', 'field' => 'media_type', 'minWidth' => 80])
            ->addTableColumn(['title' => '配文', 'field' => 'content', 'minWidth' => 120])
            ->addTableColumn(['title' => '素材', 'field' => 'media_title', 'minWidth' => 120])
            ->addTableColumn(['title' => '计划时间', 'field' => 'plan_time', 'type' => 'datetime', 'minWidth' => 180])
            ->addTableColumn(['title' => '发圈时间', 'field' => 'publish_time', 'type' => 'datetime', 'minWidth' => 180])
            ->addTableColumn(['title' => '状态', 'field' => 'status', 'minWidth' => 80,'type' => 'switch','options' => Common::status()])
            ->addTableColumn(['title' => '操作', 'minWidth' => 120, 'type' => 'toolbar'])
            ->addRightButton('edit')
            ->addRightButton('delete');

        return $builder->show();
    }

    /**
     * 发朋友圈
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function add(){
        $builder = new FormBuilder();
        $material = [];

        $data = [
            'bot_id' => [$this->bot['id']]
        ];

        $builder->setPostUrl(url('savePost'))
            ->setTip("如果只发送文本，可不选择素材。只有图片素材才可以多个，其他多媒体素材只能选一个。")
            ->addFormItem('bot_id', 'chosen_multi', '选择机器人', '选择机器人', BotService::getIdToTitle(), 'required')
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则立即发圈', [], '')
            ->addFormItem('content', 'textarea', '配文', '配文')
            ->addFormItem('media', 'choose_media_multi', '内容', '内容', ['types' => MediaService::types()])
            ->setFormData($data);

        return $builder->show(['material' => $material]);
    }

    /**
     * 发朋友圈
     * @return mixed
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function edit(){
        $id = input('id', null);
        $data = $this->model->where([
            $this->tenantWhere(),
            ['bot_id','=',$this->bot['id']]
        ])->find($id);

        if (!$data) {
            return $this->error('参数错误!');
        }

        $data['bot_id'] = explode(',', $data['bot_id']);
        $data['plan_time'] = date('Y-m-d H:i:s', $data['plan_time']);
        $builder = new FormBuilder();
        $materials = [];
        if($data['media_id']){
            $media_ids = explode(',', $data['media_id']);
            foreach ($media_ids as $media_id){
                $m = MediaService::getMedia(['id' => $media_id, 'type' => $data['media_type']]);
                $m['type'] = $data['media_type'];
                $materials[] = $m;
            }
        }

        $builder->setPostUrl(url('savePost'))
            ->setTip("如果只发送文本，可不选择素材。只有图片素材才可以多个，其他多媒体素材只能选一个。")
            ->addFormItem('id', 'hidden', 'ID', 'ID')
            ->addFormItem('bot_id', 'chosen_multi', '选择机器人', '选择机器人', BotService::getIdToTitle(), 'required')
            ->addFormItem('plan_time', 'datetime', '发送时间', '不填则立即发圈', [], '')
            ->addFormItem('content', 'textarea', '配文', '配文')
            ->addFormItem('media', 'choose_media_multi', '内容', '内容', ['types' => MediaService::types(), 'materials' => $materials])
            ->setFormData($data);

        return $builder->show();
    }

    public function savePost(Request $request, $jump_to = '', $data = [])
    {
        $post_data = input('post.');
        if(empty($post_data['content']) && count($post_data['media_id_type']) < 1){
            return $this->error('请填写配文或选择素材');
        }
        $post_data['company_id'] = TenantService::getCompanyId();
        $post_data['media_type'] = 'text';
        $msg = '发圈成功！';
        if(empty($post_data['plan_time'])){
            $post_data['plan_time'] = time();
        }else{
            $post_data['plan_time'] = strtotime($post_data['plan_time']);
            $msg = "发圈任务保存成功！";
        }

        if(!empty($post_data['media_id_type'])){
            $media_id = [];
            $media_type = '';
            foreach ($post_data['media_id_type'] as $id_type){
                list($id, $type) = explode('_', $id_type);
                $media_id[] = $id;
                $media_type = $type;
            }
            $media_id = implode(',', $media_id);
            $post_data['media_id'] = $media_id;
            $post_data['media_type'] = $media_type;
            unset($post_data['media_id_type']);
        }
        if(empty($post_data[$this->pk])){
            $res = $this->model->createOne($post_data);
        }else {
            $res = $this->model->update($post_data);
        }

        if($res){
            if($res['plan_time'] <= time()){
                MomentsService::publishMoments($res);
            }
            return $this->success($msg, $jump_to);
        }else{
            return $this->error('数据保存出错', $jump_to, ['token' => token()]);
        }
    }

    /**
     * 跟圈设置
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\Exception
     * Author: fudaoji<fdj@kuryun.cn>
     */
    public function follow()
    {
        $company_id = TenantService::getCompanyId();
        if(request()->isPost()){
            $post_data = input('post.');
            if(empty($post_data[$this->pk])){
                $post_data['company_id'] = $company_id;
                $post_data['bot_id'] = $this->bot['id'];
                $this->momentsFollowM->createOne($post_data);
            }else{
                $this->momentsFollowM->update($post_data);
            }
            return $this->success('设置成功!');
        }
        $data = $this->momentsFollowM->where([
            TenantService::companyIdWhere(),
            ['bot_id' ,'=', $this->bot['id']]
        ])
        ->find();
        !isset($data['status']) && $data['status'] = 1;
        $data['wxids'] = empty($data['wxids']) ? [] : explode(',', $data['wxids']);

        $members = FriendService::getWxidToNickname(null, [['type', '=', BotService::FRIEND]]);
        // 使用FormBuilder快速建立表单页面
        $builder = new FormBuilder();
        $builder->setMetaTitle('跟圈对象')
            ->setPostUrl(url('follow'))
            ->addFormItem('id', 'hidden', 'ID', 'ID')
            ->addFormItem('wxids', 'chosen_multi', '指定对象', '指定需要跟圈的好友', $members, 'required')
            ->addFormItem('status', 'radio', '状态', '状态', [1 => '启用', 0 => '禁用'])
            ->setFormData($data);

        return $builder->show();
    }
}